<?php
namespace jy_supplier;
defined('BY_JYA') or exit('error');
/*
	供货结算
*/
class commission extends \plugin{
	/*
		计算抽成,$add是否创建抽成订单
	*/
	function get_choufee($order_id,$add=false,$merchid=0,$isup=0){
		$merchorder=pdo_get('jy_supplier_order',array('uniacid'=>$_SESSION['uniacid'],'order_id'=>$order_id));
		if($merchorder['id']){
			$this->up_orderstatus($order_id,$merchid);
			if(!$isup){
				return $merchorder;
			}
		}
		$order=pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
		if($order['status']==0 || $order['status']==-1 || $order['status']==4){
			return $merchorder;
		}
		$params=array('uniacid'=>$_SESSION['uniacid'],'orderid'=>$order_id,'api_pluginname'=>'jy_supplier');
		if($merchid){
			$params['api_id']=$merchid;
			$merch=pdo_get('jy_supplier_user',array('uniacid'=>$_SESSION['uniacid'],'id'=>$merchid));
		}
		$goodsorder=pdo_getall('jy_weishop_order_goods',$params,array('api_id','goodsid','optionid','price','total','total_price','goodssn','productsn','goodsinfo'));
		$merchsfee=array();
		foreach($goodsorder as $item){
			if($item['api_id']){
				$item['goodsinfo']=$item['goodsinfo']?json_decode($item['goodsinfo'],true):array();
				if(!$merchid){
					$merch=pdo_get('jy_supplier_user',array('uniacid'=>$_SESSION['uniacid'],'id'=>$item['api_id']));
				}
				if($merchsfee[$item['api_id']]){
					$merchsfee[$item['api_id']]['goodsfee'] +=$item['price']*$item['total'];
				}else{
					$merchsfee[$item['api_id']]=array(
						'id'=>$item['api_id'],
						'choufee_type'=>$merch['choufee_type'],
						'choufee_set'=>$merch['choufee_set']?json_decode($merch['choufee_set'],true):array(),
						'goodsfee'=>$item['total_price'],
						'out_upfee'=>$merch['out_upfee'],
						'dispatchprice'=>$order['dispatchprice'],
						'goodsinfo'=>$item['goodsinfo'],
						'total'=>$item['total'],
					);
				}
			}
		}
		$merchnum=count($merchsfee);
		$choufee_set=$this->setting;
		foreach($merchsfee as &$mv){
			//供应价模式
			if($mv['choufee_type']){
				$mv['commission_type']=$choufee_set['commission_type'];
				$mv['commission_totalfee']=intval($mv['goodsfee']*100)/100;
				$mv['my_fee']=intval($mv['goodsinfo']['costprice']*$mv['total']*100)/100;
				$mv['commission_fee']=$mv['commission_totalfee']-$mv['my_fee'];
				continue;
			}
			$mv['dispatchprice']=$mv['dispatchprice']*1/$merchnum;
			$commission_totalfee=0;
			if($order['isdish']){
				$commission_type=$choufee_set['commission_type'];
				if($commission_type==3 && $mv['choufee_set'] && ($mv['choufee_set']['rate'] || $mv['choufee_set']['rateyuan'] || $mv['choufee_set']['ratejieti'])){
					$choufee_set=$mv['choufee_set'];
					$commission_type=$choufee_set['commission_type'];
				}
				if(strpos($choufee_set['dish_feetype'],';0;')!== false){
						$commission_totalfee +=$mv['goodsfee'];
				}
				if(strpos($choufee_set['dish_feetype'],';1;')!== false){
						$commission_totalfee +=$mv['fanhefee'];
				}
				if(strpos($choufee_set['dish_feetype'],';2;')!== false){
						$commission_totalfee +=$mv['out_upfee'];
				}
				if(strpos($choufee_set['dish_feetype'],';3;')!== false){
						$commission_totalfee +=$mv['dispatchprice'];
				}
			}else{
				$commission_type=$choufee_set['shopcommission_type'];
				if($commission_type==3 && $mv['choufee_set'] && ($mv['choufee_set']['shoprate'] || $mv['choufee_set']['shoprateyuan'] || $mv['choufee_set']['shopratejieti'])){
					$choufee_set=$mv['choufee_set'];
					$commission_type=$choufee_set['shopcommission_type'];
				}
				if(strpos($choufee_set['shop_feetype'],';0;')!== false){
						$commission_totalfee +=$mv['goodsfee'];
				}
				if(strpos($choufee_set['shop_feetype'],';3;')!== false){
						$commission_totalfee +=$mv['dispatchprice'];
				}
			}
			$commission_totalfee=$commission_totalfee?:$mv['goodsfee'];
			if(!$mv['choufee_set'] || $commission_type==0){
					$commission_fee =$commission_totalfee*$choufee_set['rate']/100;
			}elseif($commission_type==1){
					$commission_fee =$choufee_set['rateyuan'];
			}elseif($commission_type==2){
					$minrate=20;
					foreach($choufee_set['ratejieti'] as $rv){
						if(!$rv['rate'] || $rv['fee']>$commission_totalfee){
							continue;
						}
						$minrate=$rv['rate']>$minrate?$minrate:$rv['rate'];
					}
					$commission_fee =$commission_totalfee*$minrate/100;
			}elseif($commission_type==3){
					//$commission_fee =$commission_totalfee*$mv['choufee_set']['payrate']/100;
			}
			$mv['commission_type']=intval($commission_type*100)/100;
			$mv['commission_totalfee']=intval($commission_totalfee*100)/100;
			$mv['commission_fee']=intval($commission_fee*100)/100;
			$mv['my_fee']=$commission_totalfee-$commission_fee;
		}
		foreach($merchsfee as $bmv){
			if($add && !$merchorder['id']){
				$data=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$order['mid'],
					'order_id'=>$order['id'],
					'merchid'=>$bmv['id'],
					'order_price'=>$order['price'],
					'commission_type'=>$bmv['commission_type'],
					'commission_price'=>$bmv['commission_totalfee'],
					'commission_money'=>$bmv['commission_fee'],
					'isdish'=>$order['isdish'],
					'status'=>$order['status']==3?1:0,
					'createtime'=>$order['paytime']?:$order['createtime'],
				);
				$this->pdo_insert('order',$data);
			}elseif($merchorder['id']){
				pdo_update('jy_supplier_order',array('commission_money'=>$bmv['commission_fee']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$merchorder['id']));
			}
		}
		//返回最后一个商户的
		$merchorder=array(
			'status'=>0,
			'commission_type'=>$mv['commission_type'],
			'commission_price'=>intval($mv['commission_totalfee']*100)/100,
			'commission_money'=>intval($mv['commission_fee']*100)/100,
			'my_money'=>intval($mv['my_fee']*100)/100,
		);
		return $merchorder;
	}
	function up_orderstatus($order_id=0,$merchid=0){
		$merchorder=pdo_get('jy_supplier_order',array('uniacid'=>$_SESSION['uniacid'],'order_id'=>$order_id));
		if(!$merchorder['id']){
			$this->get_choufee($order_id,true,$merchid);
			return true;
		}
		$order=pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
		if($order['status']==3){
			pdo_update('jy_supplier_order',array('status'=>1),array('uniacid'=>$_SESSION['uniacid'],'order_id'=>$order_id));
		}
		return true;
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order=array()){
		if($order['id']){
			$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('orderid'=>$order['id']));
		}
	}
	/*
		创建结算单
	*/
	public function create_balance($mid){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		return true;
	}
	/*
		订单结算
	*/
	public function pay_clearing($clearing_id,$pay_type){
		$clearing=$this->get('clearing',array('id'=>$clearing_id,'uniacid'=>$_SESSION['uniacid']));
		$clearing['mid']=pdo_getcolumn('jy_supplier_user',array('uniacid'=>$_SESSION['uniacid'],'id'=>$clearing['merchid']),'mid');
		if(!$clearing || $clearing['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_type=$pay_type?:$clearing['pay_type'];
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($clearing['mid'],$clearing['finalprice'],$clearing['clearno'],'商户提现');
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'paytime'=>TIMESTAMP,
		);
		$this->update('clearing',$update,array('id'=>$clearing['id']));
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn,$remark=''){
		$remark=$remark?:'分销佣金打款';
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark);
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$remark=''){
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>$remark?:'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金比例【{$goods['commission_per']}%】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='未启用';
		}
		$remark['level_title']=pdo_getcolumn('jy_supplier_level',array('id'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
招商员等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}